﻿using System;
using System.Windows;
using System.Windows.Controls;
using CCF20Model.ConfigurationFile;
using CCF20Model;
using Microsoft.Win32;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Management;
using System.Security.Principal;
using CCF20Model.Common;
using CCF20.Resources;
using System.Collections.Generic;
using WiseLink.RDS.Resource;


namespace CCF20Module
{
    /// <summary>
    /// Interaction logic for Configuration.xaml
    /// </summary>
    public partial class Configuration : Window
    {
        const string BackupShareName = "RDSBackup";
        public Configuration()
        {
            InitializeComponent();
            DataContext = ConfiguraitonHelper.MyConfiguration;
            List<string> customerTypeSrc = new List<string> { ZICType.eRDS,ZICType.ChinaMobile};
            comboCustomerType.ItemsSource = customerTypeSrc;
            comboCustomerType.SelectedIndex = customerTypeSrc.IndexOf(ConfiguraitonHelper.MyConfiguration.customertype);
            
        }

        private string GetBackupFolder(string inputFolder)
        {
            return string.Format("{0}\\RDS.bak", inputFolder);
        }
        
        private void Submit_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            ConfiguraitonHelper.SerializeToXml();
            if (btn.Name == "btnSave")
            {
                string strResult = App.CheckConfiguration();
                if (strResult.Length > 0)
                {
                    LoggerHelper.LogCCF20(strResult);
                    Utility.ShowMessageBox("配置文件有变化，请重新启动程序");
                    App.Current.Shutdown();
                }
                else
                {
                    this.Close();
                }
            }
            else if (btn.Name == "btnBackup")
            {
                /*
                string backupFolder = GetBackupFolder(this.BackupDir.Text);
                if (!Directory.Exists(backupFolder))
                {
                    Directory.CreateDirectory(backupFolder);
                 
                }
                while (!Win32ShareWrapper.IsShareNameAvailable(BackupShareName))
                {
                    LoggerHelper.LogCCF20("DB Share Folder existing. Remove the share first");
                    Win32ShareWrapper.RemoveShare(BackupShareName);
                }

                CCF20Model.Common.User[] users = new CCF20Model.Common.User[]
                {
                    new CCF20Model.Common.User
                    {
                        UserName = string.Format("{0}\\{1}", Environment.MachineName, "Everyone"),
                        AllowFullControl = true,
                        AllowRead = false
                    }
                };
                
                string[] strReturn = null;

                string shareUNCPath = string.Empty;
                
                if (Win32ShareWrapper.CreateDirectoryShare(backupFolder, BackupShareName, "RDSBackup", users, ref shareUNCPath, ref strReturn))
                {
                    LoggerHelper.LogCCF20("[ShareFolder]AssignPermission Succeed");
                }
                else
                {
                    LoggerHelper.LogCCF20("[ShareFolder]AssignPermission Failed");
                    Utility.ShowMessageBox("数据库备份失败,共享目录授权失败");
                    return;

                }


                if (strReturn != null)
                {
                    strReturn.AsEnumerable().ToList().ForEach(msg => LoggerHelper.LogCCF20(msg));
                }


                
                string backFileName = string.Format("{0}\\{1}-{2}.bak",
                                                      shareUNCPath,
                                                      DateTime.Today.ToString("yyyy-MM-dd"),
                                                      Guid.NewGuid());
                LoggerHelper.LogCCF20(string.Format("[ShareFolder] UNCPath={0}", backFileName));

                BackupDeviceItem backupDeviceItem = new BackupDeviceItem(backFileName, DeviceType.File);
                
                
                */
                ServerConnection sqlconn = new ServerConnection(new SqlConnectionInfo(ConfiguraitonHelper.MyConfiguration.database,
                                                                                      ConfiguraitonHelper.MyConfiguration.user,
                                                                                      ConfiguraitonHelper.MyConfiguration.password));

                BackupDeviceItem backupDeviceItem = new BackupDeviceItem(GetBackupFolder(this.BackupDir.Text), DeviceType.File);
                sqlconn.LoginSecure = false;
                Server svr = new Server(sqlconn);
                Backup bkp = new Backup();
                
                bkp.Action = BackupActionType.Database;
                bkp.Database = ConfiguraitonHelper.MyConfiguration.catalog;
                bkp.Initialize = true;
                bkp.Devices.Add(backupDeviceItem);
                bkp.Incremental = false; // true = diff; false = full
                bkp.ContinueAfterError = false;
                bkp.SqlBackup(svr);
                Utility.ShowMessageBox("数据库备份成功");
            }
            else if (btn.Name == "btnRestore")
            {
                //string backupFolder = GetBackupFolder(this.BackupDir.Text);
                //DirectoryInfo dirInfo = new DirectoryInfo(backupFolder);
                //var backupFile = (from f in dirInfo.GetFiles("*.bak")
                //                  orderby f.LastWriteTime descending 
                //                  select f).FirstOrDefault();

                
                //if (backupFile == null)
                //{
                //    Utility.ShowMessageBox("没有找到数据库备份文件路径");
                //    return;
                //}
                ServerConnection sqlconn = new ServerConnection(new SqlConnectionInfo(ConfiguraitonHelper.MyConfiguration.database,
                                                                                      ConfiguraitonHelper.MyConfiguration.user,
                                                                                      ConfiguraitonHelper.MyConfiguration.password));
                sqlconn.LoginSecure = false;
                Server svr = new Server(sqlconn);
                svr.KillAllProcesses(ConfiguraitonHelper.MyConfiguration.catalog);
                //svr.Databases[0].UserAccess = DatabaseUserAccess.Single;
                svr.Databases[0].RecoveryModel = RecoveryModel.Full;
                Restore restore = new Restore();
                restore.Action = RestoreActionType.Database;
                restore.Database = ConfiguraitonHelper.MyConfiguration.catalog;
                restore.ReplaceDatabase = true;
                restore.Devices.AddDevice(GetBackupFolder(this.BackupDir.Text), DeviceType.File); 
                restore.NoRecovery = false;

                string errMsg;
                if (!restore.SqlVerify(svr, out errMsg))
                {
                    Utility.ShowMessageBox(string.Format("RDS数据库备份文件出错 {0}",errMsg));
                    return;
                }

                restore.SqlRestore(svr);
                Utility.ShowMessageBox("RDS数据库恢复成功");
            }
            
        }

        private  string ShareFolder(string FolderPath, string ShareName, string Description)
        {

            ManagementClass managementClass = new ManagementClass("Win32_Share");

            ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
            ManagementBaseObject outParams;
            inParams["Description"] = Description;
            inParams["Name"] = ShareName;
            inParams["Path"] = FolderPath;
            inParams["Type"] = 0x0; // Disk Drive
            outParams = managementClass.InvokeMethod("Create", inParams, null);
            uint returnValue = (uint)(outParams.Properties["ReturnValue"].Value);
            if (returnValue != 0 && returnValue != 22) //0-success 22-Duplicate
            {
                throw new Exception(string.Format("Unable to share directory.{0}, return={1}", FolderPath, returnValue));
            }
            else
            {
                LoggerHelper.LogCCF20(string.Format("[ShareFolder] Path={0} ShareName={1} succeed", FolderPath, ShareName));
            }


            return string.Format("\\\\{0}\\{1}", Environment.MachineName, ShareName);
            
            
                
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (Button btn in CCFBase.FindVisualChildren<Button>(this))
            {
                btn.Content = WiseLink.RDS.Resource.ButtonString.ResourceManager.GetString(btn.Name) ?? btn.Content;
            }
            foreach (Label lbl in CCFBase.FindVisualChildren<Label>(this))
            {
                lbl.Content = StringLogin.ResourceManager.GetString(lbl.Name) ?? lbl.Content;
            }
        }

    }
}
